package cn.hicard.risk.web;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.hicard.risk.common.Constant;
import cn.hicard.core.Page;
import cn.hicard.core.PageResult;
import cn.hicard.core.Where;
import cn.hicard.risk.dao.BaseDao;
import cn.hicard.risk.entity.BdMerchinfo;
import cn.hicard.risk.entity.BdTradefileinfo;
import cn.hicard.risk.entity.JzgRiskestimate;
import cn.hicard.risk.interf.merchInfo.MerchInterf;
import cn.hicard.risk.report.ReportTemplet;
import cn.hicard.risk.service.bd.MerchInfoService;
import cn.hicard.risk.service.bd.TradefileinfoService;
import cn.hicard.util.AppConfig;
import cn.hicard.util.DateHelp;
import cn.hicard.util.SpringContext;

/**
 * 向外界提供Web接口服务的Servlet
 * @author zhangy
 *
 */
public class ServiceServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	// 日志工具
	private static Logger logger = Logger.getLogger(Constant.LOGGER_MAIN);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		dispatch(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		dispatch(request,response);
	}

	/** 本Servlet的访问URL入口:/service */
	private final static String URLENTER = "/service";
	
	public void dispatch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		StringBuffer url = request.getRequestURL();
		logger.debug("请求的url:" + url);
		
		String serviceName = url.substring(url.lastIndexOf(URLENTER)+URLENTER.length());		
		logger.debug("请求的服务名称:" + serviceName);
		
		// 处理调单请求
		if("/InputCallOrder".equalsIgnoreCase(serviceName)){
			String reqStr = "";			
			CallorderAction action = new CallorderAction();
			try {
				action.execute(request, response);
				// 处理成功返回值：01
				reqStr = "01";
				logger.info("成功处理服务" + serviceName);
			} catch (Exception e) {
				// 处理成失败回值：00
				reqStr = "00";
				logger.error("处理服务" + serviceName +"时出错", e);
			}			
			
			// 设定响应内容为二进制字符的指定编码字节流
			response.setContentType("application/octet-stream");	
			ServletOutputStream os = response.getOutputStream();
			os.write(reqStr.getBytes(AppConfig.get("callorder_charset")));
			os.flush();
			os.close();
		}
		// 处理即时监控的交易数据查询请求
		else if("/realtime/tradejson".equalsIgnoreCase(serviceName)){
			response.setContentType("text/plain");
			StringBuilder json = new StringBuilder();
			json.append("[");
			TradefileinfoService service = (TradefileinfoService)SpringContext.getBean("tradefileinfoService");
			Page page = new Page();
			try {
				String p = request.getParameter("p");
				if(p == null){
					page.setIndex(1);					
				}else{
					page.setIndex(Integer.valueOf(p));
				}
				page.setSize(4);
				PageResult<BdTradefileinfo> result = null;
				for (int i=0; i<result.getDataList().size(); i++) {
					BdTradefileinfo trade = result.getDataList().get(i);
					json.append("{");
					json.append("pk:'");
					json.append(trade.getPkTradefileinfo());
					json.append("',merchno:'");json.append(trade.getMerchno());
					json.append("',termno:'");json.append(trade.getTermno());
					json.append("',wpmerchno:'");json.append(trade.getWpmerchno());
					json.append("',transdate:'");json.append(trade.getTransdate());	
					json.append("',transtime:'");json.append(trade.getTranstime());
					json.append("',cardno:'");json.append(trade.getCardno());
					json.append("',transmoney:'");json.append(trade.getTransmoney());
					json.append("',sysno:'");json.append(trade.getSysno());
					json.append("',transtype:'");json.append(trade.getTranstype());
					json.append("',cardtypename:'");json.append(trade.getCardtypename());
					json.append("'}");
					if(i < result.getDataList().size()-1){
						json.append(',');
					}
				}
			} catch (Exception e) {
				logger.error("", e);
			}
			json.append("]");
			response.setCharacterEncoding("GBK");
			response.getWriter().print(json.toString());
		}
		// 处理下载[金掌柜商户风险评估]数据报表，因为数据量可能较大所以不借用FLEX
		else if("/jzg/downloadEstimate".equalsIgnoreCase(serviceName)){
			String merchName = request.getParameter("mname");			
			if(merchName !=null){
				merchName = new String(merchName.getBytes("ISO-8859-1"));			
			}
			String merchNo = request.getParameter("mno");
			String adddateStart = request.getParameter("dts");
			String adddateEnd = request.getParameter("dte");
			
			BaseDao<JzgRiskestimate> dao = (BaseDao<JzgRiskestimate>)SpringContext.getBean("baseDao");
			String hql = "SELECT merchname,wpmerchno,merchaddr,identitycardno,addloginid,risklevel,businesstime,"
					+"predictdebitmoney,predictcreditmoney,predictsignorderavg,predictonemaxmoney,predictdaymaxmoney,"
					+"opendate,makeovermoney,businessarea,monthrentmoney,"
					+"predictmonthavgmoney,concat(predictbankcardrate,'%') AS predictbankcardrate,predictmonthmaxmoney"
					+" FROM JzgRiskestimate WHERE 1=1 ";
			Where where = new Where(JzgRiskestimate.class);
			where.addLike("merchname", merchName);
			where.addEqual("wpmerchno", merchNo);
			where.addBetween("adddatetime", adddateStart, adddateEnd);
			hql += where.queryString();
			try {
				List<Object[]> list = dao.findFieldsByHql(hql, where.getParams());
				ReportTemplet report = new ReportTemplet();
				String title = "新增商户风险评估报表";
				String descrip = "报表下载日期：" + DateHelp.date() + "         总共数据量：" + list.size();
				// 注意这里的字段顺序要与HQL查询的字段相一致
				String[] fields = new String[]{"商户名称","汇卡商户号","商户地址","法定代表人身份证号码","添加人","风险等级","营业时间",
						"预计借记卡刷卡交易额","预计月贷记卡刷卡交易额","预计单笔交易平均额","预计单笔最高交易额","预计单日最高营业额",
						"开业时间","营业场所店铺转让费","营业场所面积","营业场所月租金",
						"预计月平均营业额","预计银行卡交易比例","预计月最高营业额"};
				ByteArrayOutputStream reportStream = report.createGeneralTemplet(title, descrip, fields, list);
				// 证浏览器识别这是一个文件，不加也行
				response.addHeader("Content-Disposition", "attachment;filename="
						+ URLEncoder.encode("新增商户风险评估报表.xls", "UTF-8"));
				response.setContentLength(reportStream.size());				
				response.getOutputStream().write(reportStream.toByteArray());
			} catch (Exception e) {
				logger.error("", e);
			}
		}// 商户系统同步商户资料数据到风控系统的接口
		else if("/getMerchInfo".equalsIgnoreCase(serviceName)){
			StringBuffer result = new StringBuffer();
			BufferedReader bufferedReader = null;
			Reader reader = null;
			String line = null;	
			try{
				reader = new InputStreamReader(request.getInputStream(), "UTF-8");
				bufferedReader = new BufferedReader(reader);
				
				while ((line = bufferedReader.readLine()) != null) {
					result.append(line);
				}		
			}catch(Exception e){
				logger.error("接受商户系统商户资料出错", e);
			}
			
			 MerchInterf merchInterf=new MerchInterf();
			String returnJson= merchInterf.getMerchInfo(result.toString());
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/xml;charset=utf-8");
		   	PrintWriter out=response.getWriter();
			out.print(returnJson);	
		}// 商户信息下载灰名单功能
		else if("/merchInfo/grayReport".equalsIgnoreCase(serviceName)){
			ReportTemplet reportTemplet=new ReportTemplet();
			MerchInfoService merchInfoService = (MerchInfoService)SpringContext.getBean("merchInfoService");
			try{
			Where where=new Where(BdMerchinfo.class);
			where.setMode(Where.MODE_NOT_CHECK);
			where.addEqual("merch_degree", "4");
			List <Object[]>list=merchInfoService.getMerchReportList(where);
			String [] fileds=new String[]{"汇卡商户号","商户名称","最后修改时间","原因描述","风险级别"}; 
			//生成
			ByteArrayOutputStream reportStream  =reportTemplet.createGeneralTemplet("灰名单报表","灰名单报表",fileds,list);
			// 证浏览器识别这是一个文件，不加也行
			response.addHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode("灰名单报表.xls", "UTF-8"));
			response.setContentLength(reportStream.size());				
			response.getOutputStream().write(reportStream.toByteArray());
			}catch(Exception e){
				logger.error("灰名单报表下载出错"+e);
			}
		}
	}
}
